package com.hyy.taobao.controller;

import com.hyy.taobao.api.IMyCartService;
import com.hyy.taobao.api.entity.MyCart;
import com.hyy.taobao.api.entity.User;
import com.hyy.taobao.service.MyCartServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/insertGoods")
public class MyCartInsertGoodsServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;utf-8");
        HttpSession session = req.getSession();
        User myUser = (User) session.getAttribute("myUser");
        String userName = myUser.getUserName();
        String goodsName = req.getParameter("goodsName");
        int goodsPrice = Integer.parseInt(req.getParameter("goodsPrice"));
        String goodsNumber = req.getParameter("goodsNumber");
        if (!"".equals(goodsNumber)){
            int goodsNumber1 = Integer.parseInt(goodsNumber);
            if(goodsNumber1>0){
                MyCart myCart = new MyCart(userName,goodsName,goodsPrice,goodsNumber1);
                IMyCartService iMyCartService = new MyCartServiceImpl();
                boolean judgement = iMyCartService.myCartInsertGoods(myCart);
                if (judgement){
                    req.setAttribute("msg","加入购物车成功！");
                    req.getRequestDispatcher("goodsResult.jsp").forward(req,resp);
                }else {
                    req.setAttribute("msg","添加购物车失败！");
                    req.getRequestDispatcher("goodsResult.jsp").forward(req,resp);
                }
            }else {
                req.setAttribute("msg","请正确输入商品数量！");
                req.getRequestDispatcher("taobaoIndex.jsp").forward(req,resp);
            }
        } else {
            req.setAttribute("msg","请输入商品数量！");
            req.getRequestDispatcher("taobaoIndex.jsp").forward(req,resp);
        }
    }
}
